package com.litblue.minio.controller;

import com.litblue.minio.config.MinioTemplate;
import com.litblue.minio.res.MinioReturn;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@RestController
@RequestMapping("minio")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class MioController {

   private final MinioTemplate minioTemplate;

   @PostMapping("upload")
    MinioReturn upload(MultipartFile file){
       MinioReturn minioReturn=null;
       try {
            minioReturn = minioTemplate.putFile(file);
       } catch (Exception e) {
           throw new RuntimeException(e);
       }
       return minioReturn;
   }
   @PostMapping("remove")
     String remove(@RequestBody Map map){
       try {
           minioTemplate.removeFile(map);
       } catch (Exception e) {
           throw new RuntimeException(e);
       }
       return "success";
   }
   @PostMapping("uploadMultiple")
    List<MinioReturn> uploadMultiple(@RequestParam("files") MultipartFile[] files){
       ExecutorService executorService = Executors.newFixedThreadPool(3);
       List<CompletableFuture<MinioReturn>> collect = List.of(files).stream().map(file -> CompletableFuture.supplyAsync(() -> {
                   try {
                       return minioTemplate.putFile(file);
                   } catch (Exception e) {
                       throw new RuntimeException(e);
                   }
               }, executorService))
               .collect(Collectors.toList());
       List<MinioReturn> returnList = collect.stream().map(CompletableFuture::join).collect(Collectors.toList());
       executorService.shutdown();
       return returnList;

   }
}
